/**
 * @file frame.c
 * @brief Service looping frame implementation.
 * @author Hongbao Chen
 * @version 1.0 Beta
 * @date 2012-04-04
 */

#ifndef FRAME_H_
#include "frame.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif


/**
 * @brief This function will be called upon the termination of program after calling exit() or returning from main.
 * This function will collect the data of the currently running system and write it to log.
 */
void exitHandler1(void) {
	char buf[MAX_BUF_SIZE];
	snprintf(buf, MAX_BUF_SIZE-1, "[INFO]Process exited.");
	buf[MAX_BUF_SIZE-1] = '\0';
	API_ERR_LOG(buf);
	
}


/**
 * @brief static variable, only visible to the current file.
 */
static struct ServiceEnv Environ;
	
int main(int argc, char **argv) {

	if(atexit( exitHandler1 ) != 0) {
		API_ERR_LOG("[ERROR]atexit fail. No further information will be provided upon termination of the program by default.");
		API_ERR_STDOUT("[ERROR]atexit fail. No further information will be provided upon termination of the program.");
	}
	
	char msgBuf[MSGBUF_SIZE];
	bzero(msgBuf, MSGBUF_SIZE);

	pEnv pServiceEnv = &Environ;

	bzero(pServiceEnv, sizeof(Env) * sizeof(char));

	if(argc >1 && api_isFileExist(argv[1])) {
		if(buildServiceEnv(argv[1], pServiceEnv) == (int)-1) {
			API_ERR_LOG("[ERROR]buildServiceEnv fail. Check the program argument and the existence of struct ServiceEnv.");
			API_ERR_STDOUT("[ERROR]buildServiceEnv fail. Check the program argument and the existence of struct ServiceEnv.");
			exit(1);
		}
	} else {
		if(buildServiceEnv(DEF_INI_PATH, pServiceEnv) == (int)-1) {
			API_ERR_LOG("[ERROR]buildServiceEnv fail. Check the program argument and the existence of struct ServiceEnv.");
			API_ERR_STDOUT("[ERROR]buildServiceEnv fail. Check the program argument and the existence of struct ServiceEnv.");
			exit(1);
		}
	}

	struct IniFile *pIni = &(pServiceEnv->ini_file);
	void *handler;
	void *symbol;
	char *pValue = api_queryIni(pIni, GLB_CFG_SO_PATH, NULL, 0);
	if(pValue != (char*)NULL) {
		handler = api_soLoad(pValue);
	} else {
		handler = api_soLoad(DEF_GLB_SO_PATH);
	}
	
	/* Register the user-defined exiting handler. */
	pValue	= api_queryIni(pIni, GLB_CFG_HD_EXIT, NULL, 0);
	if(pValue != (char*)NULL && handler != (void *)NULL) {
		if((symbol = api_soSymbol(handler, pValue)) != (void *)NULL) {
			atexit((EXIT_HANDLER)symbol);
		}
	}
	
	//TODO Here, wee need to call a global method to setup functionalities, like cache, monitoring ,etc.
	//It will receive a pointer to the ServiceEnv and store information about the functionalites in pData.

	serviceFrame(argc, argv, pServiceEnv);

	return (int)0;
}








#ifdef __cplusplus
}
#endif
